<script setup lang="tsx">
import { ref, unref, reactive } from 'vue'
import { ElButton, ElDrawer, ElIcon } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { ContentWrap } from '@/components/ContentWrap'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { Search } from '@/components/Search'
import Write from './components/Write.vue'
import { useI18n } from '@/hooks/web/useI18n'
import { contentCategoryListApi, contentCategoryDeleteApi } from '@/api/college'
import type { ContentCategoryItem } from '@/api/college/types'
import { ContentPortDict, dictToList } from '@/utils/dict'

const { t } = useI18n()
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await contentCategoryListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await contentCategoryDeleteApi(unref(ids.value[0]))
    return !!res
  }
})

const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'categoryName',
    label: t('college.categoryName'),
    form: {
      colProps: {
        span: 24
      },
      componentProps: {
        placeholder: t('college.categoryNameHint')
      }
    }
  },
  {
    field: 'contentPort',
    label: t('college.contentPort'),
    search: {
      component: 'Select',
      componentProps: {
        options: dictToList(ContentPortDict)
      }
    },
    form: {
      colProps: {
        span: 24
      },
      component: 'Select',
      componentProps: {
        options: dictToList(ContentPortDict)
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{row.contentPort && ContentPortDict[row.contentPort]}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'categorySort',
    label: t('college.categorySort'),
    search: {
      hidden: true
    },
    form: {
      colProps: {
        span: 24
      },
      label: t('college.sortLabel'),
      componentProps: {
        type: 'number',
        placeholder: t('college.sortHint')
      }
    }
  },
  {
    field: 'createTime',
    label: t('college.createTime'),
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 120,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <ElButton
                v-hasPermi="POST /contentCategory/update"
                type="primary"
                link
                onClick={() => action(row, 'edit')}
              >
                {t('exampleDemo.edit')}
              </ElButton>
              <ElButton
                v-hasPermi="POST /contentCategory/delete"
                type="danger"
                link
                onClick={() => delData(data.row)}
              >
                {t('exampleDemo.del')}
              </ElButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)
const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { createTime, ...rest } = params
  let startTime, endTime
  if (createTime && createTime.length > 0) {
    startTime = createTime[0]
    endTime = createTime[1]
  }
  currentPage.value = 1
  searchParams.value = {
    startTime,
    endTime,
    ...rest
  }
  getList()
}

const showDrawer = ref(false)
const drawerTitle = ref('')

const AddAction = () => {
  drawerTitle.value = t('college.addCategory')
  currentRow.value = undefined
  showDrawer.value = true
}

const currentRow = ref<ContentCategoryItem>()
const saveLoading = ref(false)
const writeRef = ref<ComponentRef<typeof Write>>()

const action = (row: ContentCategoryItem, _type: string) => {
  drawerTitle.value = t('exampleDemo.edit')
  currentRow.value = { ...row }
  showDrawer.value = true
}

const ids = ref<number[]>([])
const delLoading = ref(false)

const delData = async (row: ContentCategoryItem | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.id]
    : elTableExpose?.getSelectionRows().map((v: ContentCategoryItem) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length, '确认删除该学堂分类？').finally(() => {
    delLoading.value = false
  })
}

const save = async () => {
  saveLoading.value = true
  const write = unref(writeRef)
  const res = await write?.submit()
  saveLoading.value = false
  if (!res) {
    return
  }
  showDrawer.value = false
  getList()
}

const onCloseDrawer = () => {
  showDrawer.value = false
  const write = unref(writeRef)
  write?.reset()
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
      />
      <div class="mb-10px">
        <ElButton v-hasPermi="'POST /contentCategory/save'" type="success" @click="AddAction">
          <ElIcon><Plus /></ElIcon>
          {{ t('college.createCategory') }}
        </ElButton>
      </div>
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>
    <ElDrawer
      :title="drawerTitle"
      v-model="showDrawer"
      direction="rtl"
      size="650px"
      @close="onCloseDrawer"
    >
      <Write ref="writeRef" :form-schema="allSchemas.formSchema" :current-row="currentRow" />

      <template #footer>
        <ElButton @click="onCloseDrawer">{{ t('common.cancel') }}</ElButton>
        <ElButton type="primary" :loading="saveLoading" @click="save">
          {{ t('exampleDemo.save') }}
        </ElButton>
      </template>
    </ElDrawer>
  </div>
</template>
